package club.xiaojiawei.linkedlist;

import java.util.ArrayList;

/**
 * @author 肖嘉威
 * @version 1.0
 * @date 6/16/22 5:54 PM
 * @question 143. 重排链表
 * @description 给定一个单链表 L 的头节点 head ，单链表 L 表示为：L0 → L1 → … → Ln - 1 → Ln
 * 请将其重新排列后变为：
 * L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
 * 不能只是单纯的改变节点内部的值，而是需要实际的进行节点交换。
 */
public class ReorderList143 {

    public static void main(String[] args) {
        ReorderList143 test = new ReorderList143();
        ListNode root = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
        test.reorderList(root);
        System.out.println(root);
    }

    /**
     * 线性表
     * 时间复杂度 O（n）
     * 空间复杂度 O（n）
     * @param head
     */
    public void reorderList(ListNode head) {
        ListNode temp = head;
        ArrayList<ListNode> list = new ArrayList<>();
        while (temp != null){
            list.add(temp);
            temp = temp.next;
        }
        if (list.size() < 3){
            return;
        }
        int left = 0, right = list.size() - 1;
        ListNode node = new ListNode();
        while (left < right){
            list.get(left).next = list.get(right);
            node.next = list.get(left);
            node = list.get(right);
            right--;
            left++;
        }
        if ((list.size() & 1) == 1){
            node.next = list.get(list.size() >> 1);
            node.next.next = null;
        }else {
            node.next = null;
        }
    }

    /**
     * 官方-寻找链表中点 + 链表逆序 + 合并链表
     * 时间复杂度 O（n）
     * 空间复杂度 O（1）
     * @param head
     */
    public void reorderList2(ListNode head) {
        if (head == null) {
            return;
        }
        ListNode mid = middleNode(head);
        ListNode l2 = mid.next;
        mid.next = null;
        l2 = reverseList(l2);
        mergeList(head, l2);
    }

    public ListNode middleNode(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }

    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode nextTemp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = nextTemp;
        }
        return prev;
    }

    public void mergeList(ListNode l1, ListNode l2) {
        ListNode l1_tmp;
        ListNode l2_tmp;
        while (l1 != null && l2 != null) {
            l1_tmp = l1.next;
            l2_tmp = l2.next;

            l1.next = l2;
            l1 = l1_tmp;

            l2.next = l1;
            l2 = l2_tmp;
        }
    }

    static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
}
